﻿using Mobile.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XF.Common.WeChat;
using XF.Meeting.Entity.Query;
using XF.Meeting.IDal;
using XF.Meeting.DAL;
using XF.Common;
using XF.Meeting.Common;

namespace Mobile
{
    public partial class Index : System.Web.UI.Page
    {
        private static readonly string webUrl = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["webUrl"]);

        protected void Page_Load(object sender, EventArgs e)

        {
            if (!IsPostBack)
            {
                //UserInfo mobile = new UserInfo();
                //    mobile.mobile = "15210402977";
                
                var code = Request.QueryString["code"];
                var mobile = GetUserInfo(code);
                mobile.mobile = mobile.userid;
                bool checkTime = true;
                if (mobile.errmsg != "ok")
                {
                    Response.Write(code+"</br>");
                    Response.Write(mobile.errmsg);
                    Response.End();
                }
                var queryId = Request.QueryString["state"];
                IMeetingDal dal = new MeetingDal();
                //包含$说明是平板过来的,3$
                if (queryId != null & queryId.Contains('$'))
                {
                    var str = queryId.Split('$');
                    var qcState = dal.GetRoomQCState(str[0]).Result;
                    if (qcState.Item1)
                    {
                        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
                        long timeStamp = (long)(DateTime.Now.AddMinutes(-10) - startTime).TotalMilliseconds;
                        if ((long.Parse(str[1]) < timeStamp))
                        {
                            // Response.Write("<script>alert('二维码已失效请重新扫码"+timeStamp+"！"+str[1]+"')</script>");
                            checkTime = false;
                        }
                        else
                        {
                            checkTime = true;
                        }
                    }
                    else
                    {
                        checkTime = true;
                    }
                    if (checkTime != true)
                    {
                        Response.Redirect(webUrl + "#/signin?notice=二维码已失效请重新扫码&isOk=" + false);
                    }
                    else
                    {
                        if (int.Parse(str[2]) > 0)
                        {

                     
                            var obj = new CRoomPadQuery()
                            {
                                phone = mobile.userid,
                                CInfoId = int.Parse(str[2]),
                                CRoomID=int.Parse(str[0])
                            };

                            signInfoByUserIdAndCInfoId(mobile, dal, obj);

                        }
                        else
                        {
                            if (str[1]=="0")
                            {
                                var data = dal.GetCInfoByRoomIdAndUserId(str[0], mobile.userid,out string error);
                                var cinfo = XF.Common.TableToList.ToList<CInfo>(data.Result).FirstOrDefault();

                                if (error=="")
                                {
                                    if (cinfo != null && cinfo.ID > 0)
                                    {
                                        var obj = new CRoomPadQuery()
                                        {
                                            phone = mobile.userid,
                                            CInfoId = cinfo.ID,
                                            CRoomID = int.Parse(str[0])
                                        };
                                        signInfoByUserIdAndCInfoId(mobile, dal, obj);
                                    }
                                }
                                 
                                
                            }
                            var sys = dal.spGetCroomInfoByRoomId(str[0], out string strError);
                            string endT = "";
                            string roomName = "";
                            if (strError == "")
                            {
                                endT = sys.Result.Tables[1].Rows[0]["endT"].ToString();
                                roomName = sys.Result.Tables[0].Rows[0]["roomName"].ToString();
                            }
                            Response.Redirect(webUrl + $"#/MeetingReservation?phone={mobile.userid}&endT={endT}&CroomId={str[0]}&CroomName={roomName}");

                        }
                        Response.Redirect(webUrl + "#/LookMeeting");
                    }



                }
                else
                {
                    Response.Redirect(webUrl + "#/MeetingReservation?phone=" + mobile.userid);
                }



            }
        }

        private void signInfoByUserIdAndCInfoId(UserInfo mobile, IMeetingDal dal, CRoomPadQuery str)
        {
            var str1 = dal.SignInCInfo(mobile.userid,str.CInfoId.ToString());
            //GetMessage("MeetRoom/SignInByPhone", JsonConvert.SerializeObject(obj));
            switch (str1.Result.Item2)
            {
                case 1://签到成功
                    Response.Redirect(webUrl + "#/signin?isOk=true");
                    break;
                case 2://已经签到跳转会议详情
                    Response.Redirect(webUrl + $"#/MeetingReservation?cInfoId={str.CInfoId}&phone={mobile.userid}");
                    break;
                case -1://签到失败
                    Response.Redirect(webUrl + "#/signIn?notice=用户不存在！&isOk=false");
                    break;
                case 0:
                    var sys = dal.spGetCroomInfoByRoomId(str.CRoomID.ToString(), out string strError);
                    string endT = "";
                    string roomName = "";
                    if (strError == "")
                    {
                        endT = sys.Result.Tables[1].Rows[0]["endT"].ToString();
                        roomName = sys.Result.Tables[0].Rows[0]["roomName"].ToString();
                    }
                    Response.Redirect(webUrl + $"#/MeetingReservation?phone={mobile.userid}&endT={endT}&CroomId={str.CRoomID}&CroomName={roomName}");
                    break;
                default:
                    break;
            }
        }

        private UserInfo GetUserInfo(string code)
        {
            var wx = new WeChatHelper();
            var userId = wx.GetUserId(code);
            return JsonConvert.DeserializeObject<UserInfo>(wx.GetUserInfo(userId));
        }
    }
}